package com.klm.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.klm.cache.TranslateCache;
import com.klm.cache.TranslateCacheFactory;
import com.klm.common.config.LsCoreProperties;
import com.klm.common.constant.BaseConstant;
import com.klm.common.exception.BaseException;
import com.klm.common.util.BaseDateUtils;
import com.klm.dao.AutoLanguageContentDao;
import com.klm.dao.AutoLanguageItemDao;
import com.klm.entity.AutoLanguageContentEntity;
import com.klm.entity.AutoLanguageItemEntity;
import com.klm.enumeration.LangCodeEnum;
import com.klm.service.TranslateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.klm.model.*;
import com.klm.cache.TranslateCacheManager;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wq
 */
@Slf4j
@Service("TranslateService")
public class TranslateServiceImpl implements TranslateService {

    private static final String DATABASE_CODE = "SYS";

    /**
     * Redis中存储语言包的key值 FW:LANG:SYS:item_key
     */
    private static final String CACHE_KEY_LANG_PREFIX = "KLM:TRAN:LANG:SYS:";

    @Autowired
    private LsCoreProperties lsCoreProperties;
    @Autowired
    private TranslateCacheFactory cacheFactory;
    @Autowired
    private AutoLanguageItemDao autoLanguageItemDao;
    @Autowired
    private AutoLanguageContentDao autoLanguageContentDao;
    @Autowired
    private TranslateCacheManager cacheManager;

    /**
     * 根据fromTable和fromField、fromDataId获取语言包内容
     * @param fromTable 业务表名
     * @param fromField 业务字段名
     * @param fromDataId 業務ID
     * @return 语言包的唯一key值
     */
    @Override
    public ComLangModel getLangContentByFrom(String fromTable, String fromField, String fromDataId){
        ComLangModel comLangModel = new ComLangModel();

        if (fromDataId == null) {
            throw new BaseException("fromDataId不能为空");
        }
        if (StringUtils.isEmpty(fromTable) || StringUtils.isEmpty(fromField)) {
            throw new BaseException("业务表名、字段名不可为空！");
        }

       LambdaQueryWrapper<AutoLanguageItemEntity> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(AutoLanguageItemEntity::getFromTable, fromTable);
       queryWrapper.eq(AutoLanguageItemEntity::getFromField, fromField);
       queryWrapper.eq(AutoLanguageItemEntity::getFromDataId, fromDataId);
       queryWrapper.eq(AutoLanguageItemEntity::getDeleted, BaseConstant.DeleteFlag.NOT_DELETED);
       queryWrapper.last("LIMIT 1");
       AutoLanguageItemEntity itemEntity = autoLanguageItemDao.selectOne(queryWrapper);
       if (itemEntity != null) {
           log.debug("[Trans. plugin] 獲取到語言包的唯一key值{}，功能代碼：{}，字段代碼：{}", itemEntity.getItemKey(),fromTable, fromField);
           comLangModel =  this.getFullContentByItemKey(itemEntity.getItemKey());
       } else {
           log.warn("[Trans. plugin] 未查詢到語言包信息，功能代碼：{}，字段代碼：{}", fromTable, fromField);
       }
       return comLangModel;
    }



    /**
     * 获取语言包的唯一key值
     * @param fromTable 业务表名
     * @param fromField 业务字段名
     * @param description 描述/备注
     * @param operator 操作人
     * @return 语言包的唯一key值
     */
    @Override
    public String getUniqueItemKey(String fromTable,String fromField,String description,String operator){
        log.info("[Trans. plugin] 獲取語言包的唯一key值，業務表名：{}，業務字段名：{}", fromTable,fromField);
        if (StringUtils.isEmpty(fromTable) || StringUtils.isEmpty(fromField)) {
            throw new BaseException("業務表名、字段名不可為空！");
        }
        log.info("[Trans. plugin] 獲取語言包的唯一key值，功能代碼：{}，字段代碼：{}",fromTable, fromField);

        String langKey = generateLangKey();
        AutoLanguageItemEntity itemEntity = new AutoLanguageItemEntity();
        itemEntity.setItemKey(langKey);
        itemEntity.setFromDatabase(DATABASE_CODE);
        itemEntity.setFromTable(fromTable);
        itemEntity.setFromField(fromField);
        itemEntity.setMemo(description);
        itemEntity.setDeleted(BaseConstant.DeleteFlag.NOT_DELETED);
        itemEntity.setUpdateTime(LocalDateTime.now());
        itemEntity.setInsertTime(LocalDateTime.now());
        itemEntity.setInsertUserId(operator);
        itemEntity.setUpdateUserId(operator);
        autoLanguageItemDao.insert(itemEntity);
        try {
            ComLangModel comLangModel = new ComLangModel();
            ComLangItemModel comLangItemModel = new ComLangItemModel(fromTable, fromField, langKey,null);
            comLangModel.setItemModel(comLangItemModel);
            comLangModel.setContentList(new ArrayList<>());
            // 默认1小时有效期
            TranslateCache cacheService = cacheFactory.createCacheService();
            if (cacheService != null) {
                cacheService.set(CACHE_KEY_LANG_PREFIX + langKey, JSONObject.toJSONString(comLangModel),null);
            }
        } catch (Exception e) {
            log.error("[Trans. plugin] 獲取語言包的唯一key值失败", e);
        }
        log.info("[Trans. plugin] 獲取語言包的唯一key值，功能代碼：{}，字段代碼：{},返回值：{}", fromTable, fromField, langKey);
        return langKey;
    }

    /**
     * 獲取完整語言包內容
     * @param itemKey 表名/功能代碼
     * @return 语言包的唯一key值
     */
    @Override
    public ComLangModel getFullContentByItemKey(String itemKey){
        log.info("[Trans. plugin] 当前使用的数据源是： {}", DynamicDataSourceContextHolder.peek());

        List<ComLangContentModel> contentList = new ArrayList<>();
        ComLangModel comLangModel = null;
        // 查询缓存
        TranslateCache cacheService = cacheFactory.createCacheService();
        if (cacheService != null) {
            comLangModel = cacheService.get(CACHE_KEY_LANG_PREFIX + itemKey, ComLangModel.class);
        }
        // 存在多语系内容
        if (comLangModel != null && comLangModel.getContentList() != null && !comLangModel.getContentList().isEmpty()) {
            return comLangModel;
        } else {
            if (comLangModel == null) {
                comLangModel = new ComLangModel();
                LambdaQueryWrapper<AutoLanguageItemEntity> itemWrapper = new LambdaQueryWrapper<>();
                itemWrapper.eq(AutoLanguageItemEntity::getItemKey, itemKey);
                itemWrapper.orderByDesc(AutoLanguageItemEntity::getUpdateTime);
                itemWrapper.last("LIMIT 1");
                AutoLanguageItemEntity itemEntity = autoLanguageItemDao.selectOne(itemWrapper);
                if (itemEntity != null) {
                    comLangModel.setItemModel(new ComLangItemModel(itemEntity.getItemKey(), itemEntity.getFromTable(), itemEntity.getFromField(), itemEntity.getFromDataId()));
                }
            }
            // 查询语言包信息
            comLangModel.setContentList(getLangContentListByItemKey(itemKey));
            // 刷新緩存
            if (cacheService != null) {
                LambdaQueryWrapper<AutoLanguageItemEntity> itemQueryWrapper = new LambdaQueryWrapper<>();
                itemQueryWrapper.eq(AutoLanguageItemEntity::getItemKey, itemKey);
                itemQueryWrapper.eq(AutoLanguageItemEntity::getDeleted, BaseConstant.DeleteFlag.NOT_DELETED);
                AutoLanguageItemEntity itemEntity = autoLanguageItemDao.selectOne(itemQueryWrapper);
                if (itemEntity != null) {
                    comLangModel.setItemModel(new ComLangItemModel(itemEntity.getItemKey(), itemEntity.getFromTable(), itemEntity.getFromField(),
                            itemEntity.getFromDataId()));
                }
                cacheService.set(CACHE_KEY_LANG_PREFIX + itemKey, comLangModel,null);
            }
        }
        return comLangModel;
    }

    private List<ComLangContentModel> getLangContentListByItemKey(String itemKey){
        List<ComLangContentModel> contentList = new ArrayList<>();
        // 查询语言包信息
        LambdaQueryWrapper<AutoLanguageContentEntity> contentQueryWrapper = new LambdaQueryWrapper<>();
        contentQueryWrapper.eq(AutoLanguageContentEntity::getItemKey, itemKey);
        contentQueryWrapper.eq(AutoLanguageContentEntity::getDeleted, BaseConstant.DeleteFlag.NOT_DELETED);
        List<AutoLanguageContentEntity> entityList = autoLanguageContentDao.selectList(contentQueryWrapper);
        // 查询已设定过的语言内容
        if (!entityList.isEmpty()) {
            // 系統當前開啟的語種列表
            List<ComLangCodeModel> langCodeList = this.getLangCodeList();
            // 提取 contentList 中的 langCode 字段
            Set<String> codeList = langCodeList.stream()
                    .map(ComLangCodeModel::getLangCode)
                    .collect(Collectors.toSet());

            for (AutoLanguageContentEntity contentEntity : entityList) {
                // 已關閉的語種，不在返回
                if (codeList.contains(contentEntity.getLangCode())) {
                    ComLangContentModel model = new ComLangContentModel(contentEntity.getItemKey(),
                            contentEntity.getLangCode(),
                            LangCodeEnum.getLangTextByCode(contentEntity.getLangCode()),
                            contentEntity.getLanguageContent());
                    contentList.add(model);
                    codeList.remove(contentEntity.getLangCode());
                }
            }
            // 新開啟的語種，構建空結構
            if (!codeList.isEmpty()) {
                for (String langCode : codeList) {
                    // 是否是有效的语言
                    if (LangCodeEnum.contains(langCode)) {
                        ComLangContentModel comLangContentModel = new ComLangContentModel(itemKey, langCode, LangCodeEnum.getLangTextByCode(langCode), "");
                        contentList.add(comLangContentModel);
                    }
                }
            }
        } else {
            // 自动构建全语种的语言内容结构
            List<String> list = lsCoreProperties.getBase().language().enable_locale_list();
            for (String langCode : list) {
                // 是否是有效的语言
                if (LangCodeEnum.contains(langCode)) {
                    ComLangContentModel comLangContentModel = new ComLangContentModel(itemKey, langCode, LangCodeEnum.getLangTextByCode(langCode), "");
                    contentList.add(comLangContentModel);
                }
            }
        }

        return contentList;
    }

    /**
     * 根據語言唯一key值，獲取Header设定语种的語言内容
     * @param itemKey 表名/功能代碼
     * @return 语言包的唯一key值
     */
    @Override
    public ComLangContentModel getSingleContentByItemKey(String itemKey){
        String langCode = LangCodeEnum.getHeaderLangCode();
        log.info("[Trans. plugin] 獲取Header设定语种的語言内容，唯一key值：{}，语言代碼：{}", itemKey, langCode);
        return this.getLangContentByItemKey(itemKey, langCode);
    }

    /**
     * 根據語言唯一key值，獲取語言包内容
     * @param itemKey 表名/功能代碼
     * @return 语言包的唯一key值
     */
    @Override
    public ComLangContentModel getLangContentByItemKey(String itemKey, String langCode){
        log.info("[Trans. plugin] 获取语言包内容，唯一key值：{}，语言代碼：{}", itemKey, langCode);
        ComLangModel comLangModel = this.getFullContentByItemKey(itemKey);
        if (comLangModel != null && comLangModel.getContentList() != null && !comLangModel.getContentList().isEmpty()) {
            List<ComLangContentModel> contentList = comLangModel.getContentList().stream()
                    .filter(content -> langCode.equals(content.getLangCode())).toList();
            if (!contentList.isEmpty()) {
                return contentList.get(0);
            } else {
                log.warn("[Trans. plugin] 未查詢到目標語言的語言包內容，唯一key值：{}，语言代碼：{}", itemKey, langCode);
                return null;
            }
        } else {
            log.warn("[Trans. plugin] 未查詢到語言包信息，唯一key值：{}，语言代碼：{}", itemKey, langCode);
            return null;
        }
    }

    /**
     * 新增/更新指定語種語言内容
     * @param itemKey 语言包的唯一key值
     * @param langCode 语言代碼 英語（en）,英語美國（en-US），中文（cn),简体中文（zh_CN），繁体中文（zh_TW） 等
     * @param content 语言包内容
     * @return 是否新增成功
     */
    @Override
    public Boolean saveContentByItemKey(String itemKey, String langCode, String content, String operator) {
        log.info("[Trans. plugin] 保存语言内容，itemKey: {}, langCode: {}", itemKey, langCode);
        try {
            // 查询语言包信息
            ComLangModel comLangModel = getFullContentByItemKey(itemKey);
            // 更新语言内容
            comLangModel.updateLangContent(langCode, content);
            // 更新语言内容
            LambdaUpdateWrapper<AutoLanguageContentEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(AutoLanguageContentEntity::getItemKey, itemKey);
            updateWrapper.eq(AutoLanguageContentEntity::getLangCode, langCode);
            updateWrapper.set(AutoLanguageContentEntity::getLanguageContent, content);
            updateWrapper.set(AutoLanguageContentEntity::getUpdateTime, LocalDateTime.now());
            updateWrapper.set(AutoLanguageContentEntity::getUpdateUserId, operator);
            if (autoLanguageContentDao.update(updateWrapper) == 0) {
                // DB插入数据
                AutoLanguageContentEntity contentEntity = new AutoLanguageContentEntity();
                contentEntity.setItemKey(itemKey);
                contentEntity.setLangCode(langCode);
                contentEntity.setLanguageContent(content);
                contentEntity.setDeleted(BaseConstant.DeleteFlag.NOT_DELETED);
                contentEntity.setInsertTime(LocalDateTime.now());
                contentEntity.setUpdateTime(LocalDateTime.now());
                contentEntity.setInsertUserId(operator);
                contentEntity.setUpdateUserId(operator);
                autoLanguageContentDao.insert(contentEntity);
            }
            // 刷新缓存
            cacheManager.refreshItemCache(itemKey);
            return true;
        } catch (Exception e) {
            log.error("[Trans. plugin] 保存语言内容失败", e);
            return false;
        }
    }

    /**
     * 獲取語種列表
     * @return 語種列表
     */
    @Override
    public ComLangCodeModel getDefaultLangCode(){
        lsCoreProperties.getBase().language().default_locale();
        for (LangCodeEnum codeEnum : LangCodeEnum.values()) {
            if (codeEnum.getLangCode().equals(lsCoreProperties.getBase().language().default_locale())) {
                ComLangCodeModel langCodeModel = new ComLangCodeModel();
                langCodeModel.setLangCode(codeEnum.getLangCode());
                langCodeModel.setLangText(codeEnum.getLangText());
                return langCodeModel;
            }
        }
        return null;
    }

    /**
     * 獲取語種列表
     * @return 語種列表
     */
    @Override
    public List<ComLangCodeModel> getLangCodeList(){
        List<ComLangCodeModel> langCodeList = new ArrayList<>();
        List<String> enableLocaleList = lsCoreProperties.getBase().language().enable_locale_list();
        for (LangCodeEnum codeEnum : LangCodeEnum.values()) {
            if (enableLocaleList != null && enableLocaleList.contains(codeEnum.getLangCode())) {
                ComLangCodeModel langCodeModel = new ComLangCodeModel();
                langCodeModel.setLangCode(codeEnum.getLangCode());
                langCodeModel.setLangText(codeEnum.getLangText());
                langCodeList.add(langCodeModel);
            }
        }
        return langCodeList;
    }

    @Override
    public Page<ComTableFieldModel> getFromTableAndFieldList(int pageNum, int pageSize) {
        pageNum = pageNum <= 0 ? 1 : pageNum;
        // 单页不超过 1000
        pageSize = Math.min(pageSize, 1000);

        MPJLambdaWrapper<AutoLanguageItemEntity> wrapper = new MPJLambdaWrapper<>();
        wrapper.eq(AutoLanguageItemEntity::getDeleted, BaseConstant.DeleteFlag.NOT_DELETED);
        wrapper.selectAs(AutoLanguageItemEntity::getFromTable, ComTableFieldModel::getFromTable);
        wrapper.selectAs(AutoLanguageItemEntity::getFromField, ComTableFieldModel::getFromField);
        wrapper.groupBy(AutoLanguageItemEntity::getFromTable, AutoLanguageItemEntity::getFromField);
        wrapper.orderByAsc(AutoLanguageItemEntity::getFromTable, AutoLanguageItemEntity::getFromField);
        Page<ComTableFieldModel> page = new Page<>(pageNum, pageSize);
        return autoLanguageItemDao.selectJoinPage(page, ComTableFieldModel.class,wrapper);
    }

    /**
     * 固定值SL+ 來源区分（00）+ yyMMddHHmmss + 4位随機敷
     * 例：SL002408291537436982（共12位）
     */
    private String generateLangKey(){
        String code = "SL".concat("00");
        // 獲取當前年月日时分秒
        String code1 = BaseDateUtils.parseLocalDateTime2String(LocalDateTime.now(), "yyMMddHHmmss");
        // 生成4位隨機數
        Random random = new Random();
        int randomNumber = random.nextInt(9999) + 1000;
        String code3 = String.valueOf(randomNumber);
        return code + code1 + code3;
    }

    /**
     * 一次性保存整个语言包的内容
     * @param saveLangContentModel 保存语言包内容的Model
     * @return 是否保存成功
     */
    @Override
    public Boolean saveFullContentByItemKey(SaveLangContentModel saveLangContentModel) {
        log.info("[Trans. plugin] 保存完整语言包内容");
        if (saveLangContentModel == null || saveLangContentModel.getItemModel() == null || saveLangContentModel.getContentList() == null) {
            log.error("[Trans. plugin] 语言包内容不能为空");
            return false;
        }

        String itemKey = saveLangContentModel.getItemModel().getItemKey();
        if (StringUtils.isEmpty(itemKey)) {
            log.error("[Trans. plugin] 语言包key值不能为空");
            return false;
        }

        try {
            String operator = saveLangContentModel.getOperator();
            // 遍历所有语言内容
            for (ComLangContentModel contentModel : saveLangContentModel.getContentList()) {
                if (StringUtils.isEmpty(contentModel.getLangCode()) || StringUtils.isEmpty(contentModel.getLanguageContent())) {
                    continue;
                }
                // 使用saveContentByItemKey方法保存每个语言内容
                saveContentByItemKey(itemKey, contentModel.getLangCode(), contentModel.getLanguageContent(), operator);
            }
            // 刷新缓存
            cacheManager.refreshItemCache(itemKey);
            return true;
        } catch (Exception e) {
            log.error("[Trans. plugin] 保存完整语言包内容失败", e);
            return false;
        }
    }

    private Page<AutoLanguageItemModel> priGetLanguageItemPage(Integer pageNum, Integer pageSize,
                                                                                               Map<String, JSONObject> params) {
        // 设置默认值
        pageNum = pageNum == null || pageNum <= 0 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize <= 0 ? 20 : pageSize;

//        log.info("分頁查詢語言包列表，頁碼：{}，每頁大小：{}，語言包key：{}，來源表名：{}，來源字段名：{}，描述：{}",
//                pageNum, pageSize, itemKey, fromTable, fromField, memo);

        // 创建分页对象
        Page<AutoLanguageItemEntity> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<AutoLanguageItemEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AutoLanguageItemEntity::getDeleted, BaseConstant.DeleteFlag.NOT_DELETED);
        // 添加可选条件
        JSONObject itemKey = params.get("itemKey");
        if (itemKey.getBoolean("condition")) {
            queryWrapper.eq(AutoLanguageItemEntity::getItemKey, itemKey.getString("value"));
        }
        JSONObject fromTable = params.get("fromTable");
        if (fromTable.getBoolean("condition")) {
            queryWrapper.like(AutoLanguageItemEntity::getFromTable, fromTable.getString("value"));
        }
        JSONObject fromField = params.get("fromField");
        if (fromField.getBoolean("condition")) {
            queryWrapper.like(AutoLanguageItemEntity::getFromField, fromField.getString("value"));
        }
        JSONObject fromDataId = params.get("fromDataId");
        if (fromDataId.getBoolean("condition")) {
            queryWrapper.like(AutoLanguageItemEntity::getFromDataId, fromDataId.getString("value"));
        }
        JSONObject memo = params.get("memo");
        if (memo.getBoolean("condition")) {
            queryWrapper.like(AutoLanguageItemEntity::getMemo, memo.get("value"));
        }

        // 按更新时间倒序排序
        queryWrapper.orderByDesc(AutoLanguageItemEntity::getUpdateTime);

        // 执行分页查询
        Page<AutoLanguageItemEntity> entityPage = autoLanguageItemDao.selectPage(page, queryWrapper);

        // 转换为Model
        Page<AutoLanguageItemModel> modelPage = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        List<AutoLanguageItemModel> modelList = entityPage.getRecords().stream()
                .map(entity -> {
                    AutoLanguageItemModel model = new AutoLanguageItemModel();
                    model.setItemId(entity.getItemId());
                    model.setItemKey(entity.getItemKey());
                    model.setFromDatabase(entity.getFromDatabase());
                    model.setFromTable(entity.getFromTable());
                    model.setFromField(entity.getFromField());
                    model.setFromDataId(entity.getFromDataId());
                    model.setMemo(entity.getMemo());
                    model.setDeleted(entity.getDeleted());
                    model.setUpdateTime(entity.getUpdateTime());
                    model.setInsertTime(entity.getInsertTime());
                    model.setUpdateUserId(entity.getUpdateUserId());
                    model.setInsertUserId(entity.getInsertUserId());
                    return model;
                })
                .toList();
        modelPage.setRecords(modelList);

        return modelPage;
    }

    @Override
    public Page<AutoLanguageItemModel> getLanguageItemPage(Integer pageNum, Integer pageSize,
                                                                                           String itemKey, String fromTable, String fromField, String fromDataId, String memo) {
        Map<String, JSONObject> params = new HashMap<>();
        params.put("itemKey", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(itemKey) ? "true" : "false") + ",\"value\":\"" + itemKey + "\"}"));
        params.put("fromTable", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(fromTable) ? "true" : "false") + ",\"value\":\"" + fromTable + "\"}"));
        params.put("fromField", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(fromField) ? "true" : "false") + ",\"value\":\"" + fromField + "\"}"));
        params.put("fromDataId", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(fromDataId) ? "true" : "false") + ",\"value\":\"" + fromDataId + "\"}"));
        params.put("memo", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(memo) ? "true" : "false") + ",\"value\":\"" + memo + "\"}"));
        return priGetLanguageItemPage(pageNum, pageSize, params);
    }

    @Override
    public Page<AutoLanguageItemModel> getNoMasterLanguageItemPage(Integer pageNum, Integer pageSize,
                                                                                                   String itemKey, String fromTable, String fromField, String memo) {
        Map<String, JSONObject> params = new HashMap<>();
        params.put("itemKey", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(itemKey) ? "true" : "false") + ",\"value\":\"" + itemKey + "\"}"));
        params.put("fromTable", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(fromTable) ? "true" : "false") + ",\"value\":\"" + fromTable + "\"}"));
        params.put("fromField", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(fromField) ? "true" : "false") + ",\"value\":\"" + fromField + "\"}"));
        params.put("fromDataId", JSONObject.parseObject("{\"condition\":true,\"value\":NULL}"));
        params.put("memo", JSONObject.parseObject("{\"condition\":" + (StringUtils.isNotEmpty(memo) ? "true" : "false") + ",\"value\":\"" + memo + "\"}"));
        return priGetLanguageItemPage(pageNum, pageSize, params);
    }

    @Override
    public Boolean logicDelLanguageContent(String itemKey, String fromDataId, String operator) {
        log.info("[Trans. plugin] 逻辑删除语言内容，itemKey: {}, fromDataId: {}", itemKey, fromDataId);
        if (StringUtils.isEmpty(itemKey) && StringUtils.isEmpty(fromDataId)) {
            log.error("[Trans. plugin] itemKey和fromDataId不能同时为空");
            return false;
        }
        try {
            // 构建更新条件
            LambdaUpdateWrapper<AutoLanguageItemEntity> updateWrapper = new LambdaUpdateWrapper<>();
            if (StringUtils.isNotEmpty(itemKey)) {
                updateWrapper.eq(AutoLanguageItemEntity::getItemKey, itemKey);
            }
            if (StringUtils.isNotEmpty(fromDataId)) {
                updateWrapper.eq(AutoLanguageItemEntity::getFromDataId, fromDataId);
            }
            updateWrapper.eq(AutoLanguageItemEntity::getDeleted, BaseConstant.DeleteFlag.NOT_DELETED);
            // 設置更新内容
            updateWrapper.set(AutoLanguageItemEntity::getDeleted, BaseConstant.DeleteFlag.IS_DELETED);
            updateWrapper.set(AutoLanguageItemEntity::getUpdateTime, LocalDateTime.now());
            updateWrapper.set(AutoLanguageItemEntity::getUpdateUserId, operator);

            // 执行更新
            int count = autoLanguageItemDao.update(null, updateWrapper);
            log.info("[Trans. plugin] 逻辑删除多语言内容，itemKey：{}，fromDataId：{}，删除记录数：{}", itemKey, fromDataId, count);

            // 刷新缓存
            cacheManager.refreshItemCache(itemKey);
            return true;
        } catch (Exception e) {
            log.error("[Trans. plugin] 逻辑删除语言内容失败", e);
            return false;
        }
    }

    @Override
    public Integer delLanguageContentBeforeDate(LocalDateTime beforeDate, String operator) {
        if (beforeDate == null) {
            log.error("[Trans. plugin] 指定日期為空");
            return 0;
        }
        try {
            // 構建更新条件
            LambdaUpdateWrapper<AutoLanguageItemEntity> deleteWrapper = new LambdaUpdateWrapper<>();
            deleteWrapper.lt(AutoLanguageItemEntity::getUpdateTime, beforeDate);
            deleteWrapper.eq(AutoLanguageItemEntity::getDeleted, BaseConstant.DeleteFlag.NOT_DELETED);
            // 執行刪除
            int count = autoLanguageItemDao.delete(deleteWrapper);
            log.info("[Trans. plugin] 刪除指定日期之前的多語言内容，指定日期：{}，刪除記錄數：{}", beforeDate, count);
            return count;
        } catch (Exception e) {
            log.error("[Trans. plugin] 刪除指定日期之前的多語言内容失敗", e);
            return 0;
        }
    }

    /**
     * 批量更新緩存
     * @return 是否更新成功
     */
    @Override
    public Boolean refreshRedis() {
        log.info("[Trans. plugin] 开始刷新Redis缓存");
        try {
            cacheManager.refreshAllCache();
            return true;
        } catch (Exception e) {
            log.error("[Trans. plugin] 刷新Redis缓存失败", e);
            return false;
        }
    }
}
